<template >
    <div>
      <el-card class="filter-container" shadow="never">
        <div>
          <i class="el-icon-search"></i>
          <span>筛选搜索</span>
          <el-button style="float:right; margin-right: 30px" type="success" @click="exportExcel">导出</el-button>
  
          <el-button style="float:right; margin-right: 15px" @click="uploadExcel()">上传</el-button>
  
          <el-button style="float:right; margin-right: 30px" type="primary" @click="getOutputtableList()">查询</el-button>
          <el-button style="float:right; margin-right: 15px" @click="handleResetSearch()">重置</el-button>
        </div>
        <!-- 文件上传窗口 -->
        <el-dialog v-model="uploadDialogVisible" title="上传文件" width="600px">
            <el-upload class="upload-demo" drag action="" :show-file-list="false" :before-upload="handleBeforeUpload"
              :on-change="handleFileChange">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">点击或拖拽文件(.xlsx)到此区域进行上传</div>
            </el-upload>
            <el-table :data="uploadedData" v-if="uploadedData.length">
              <el-table-column prop="年份" label="年份" />
              <el-table-column prop="城市" label="城市" />
              <el-table-column prop="小麦播种面积" label="小麦播种面积" />
              <el-table-column prop="玉米播种面积" label="玉米播种面积" />
              <el-table-column prop="小麦产量" label="小麦产量" />
              <el-table-column prop="玉米产量" label="玉米产量" />
              <el-table-column prop="小麦单位面积产量" label="小麦单位面积产量" />
              <el-table-column prop="玉米单位面积产量" label="玉米单位面积产量" />
          </el-table>
            <template #footer>
              <el-button @click="uploadData">上传</el-button>
              <el-button @click="uploadDialogVisible = false">取 消</el-button>
            </template>
          </el-dialog>
          <div style="margin-top: 30px; ">
          <el-form style="display: inline-block;">
            <div style="display: inline-block;margin-left:20px">
              <el-form-item label="年份：">
                <el-input class="input-width" placeholder="年份" v-model="queryParams.param.year" clearable></el-input>
              </el-form-item>
            </div>
            <div style="display: inline-block;margin-left:20px">
              <el-form-item label="城市：">
                <el-input class="input-width" placeholder="城市" v-model="queryParams.param.city" clearable></el-input>
              </el-form-item>
            </div>
          </el-form>
        </div>
      </el-card>
      <el-table ref="multipleTableRef" :data="TableList" style="width:100%" :broder="true" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="year" label="年份" />
        <el-table-column prop="city" label="城市" />
        <el-table-column prop="wheatArea" label="小麦播种面积" />
        <el-table-column prop="cornArea" label="玉米播种面积" />
        <el-table-column prop="wheatProduct" label="小麦产量" />
        <el-table-column prop="cornProduct" label="玉米产量" />
        <el-table-column prop="wheatProductUnit" label="小麦单位面积产量" />
        <el-table-column prop="cornProductUnit" label="玉米单位面积产量" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)" type="primary">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteItem(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 编辑表单 -->
      <el-dialog v-model="dialogFormVisible" :before-close="beforeClose" title="修改信息" width="800">
      <el-form ref="formRef" :model="updateForm" :rules="rules">
        <el-form-item prop="year" label="年份：">
          <el-input v-model="updateForm.year" />
        </el-form-item>
        <el-form-item prop="city" label="城市：">
          <el-input v-model="updateForm.city" />
        </el-form-item>
        <el-form-item prop="wheatArea" label="小麦播种面积：">
          <el-input v-model="updateForm.wheatArea" />
        </el-form-item>
        <el-form-item prop="cornArea" label="玉米播种面积：">
          <el-input v-model="updateForm.cornArea" />
        </el-form-item>
        <el-form-item prop="wheatProduct" label="小麦产量：">
          <el-input v-model="updateForm.cornArea" />
        </el-form-item>
        <el-form-item prop="cornProduct" label="玉米产量：">
          <el-input v-model="updateForm.cornProduct" />
        </el-form-item>
        <el-form-item prop="wheatProductUnit" label="小麦单位面积产量：">
          <el-input v-model="updateForm.wheatProductUnit" />
        </el-form-item>
        <el-form-item prop="cornProductUnit" label="玉米单位面积产量：">
          <el-input v-model="updateForm.cornProductUnit" />
        </el-form-item>
      </el-form>
      <el-button type="primary" style="margin-left: 50%;" @click="confirm()">提交</el-button>
    </el-dialog>

      <!-- 分页 -->
     <div>
      <el-pagination :current-page="queryParams.pageNum" :page-size="queryParams.pageSize" :page-sizes="[15, 30, 45]"
        :small="false" :disabled="false" :background="true" layout="total, sizes, prev, pager, next, jumper"
        :total="total" @size-change="handleSizeChange" @current-change="handleNumChange" />
    </div>
    </div>
  </template>
  
<script setup>
import { fetchOutputTablePage,updateOutputTable,deleteOutputTable,uploadOutputTable} from "../../../api/crops";
import { nextTick, ref, reactive, onMounted, VueElement } from "vue";
import * as XLSX from "xlsx";

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  param: {
    year:'',
    city:''
  }
});

//获得列表
const TableList = ref([]); // 直接使用 ref 定义数组
let total = ref(0);

function getOutputtableList(){
  console.log("queryparam",queryParams.param);
  fetchOutputTablePage(queryParams)
  .then(res =>{
    console.log('res',res)
    TableList.value = res.data.result.records; 
      total.value = res.data.result.total;
      // console.log("tower", towersList.value);
      console.log('queryParams.value', queryParams.param)
  })
  .catch(error=>{
    console.log("Error fetching drones list:",error);
  })
}

//重置事件
const handleResetSearch = async () => {
  queryParams.param.year = '',
  queryParams.param.city = '',
  getOutputtableList();
}
//更改每页显示数量
const handleSizeChange = val => {
  queryParams.pageSize = val;
  getOutputtableList();
};

//更换页数
const handleNumChange = val => {
  queryParams.pageNum = val;
  getOutputtableList();
};

//编辑功能
const dialogFormVisible = ref(false);
const formRef = ref();

const updateForm = ref({
  city: '',
  cornArea: '',
  cornProduct: '',
  cornProductUnit: '',
  id: '',
  wheatArea: '',
  wheatProduct: '',
  wheatProductUnit: '',
  year: ''
});

const handleEdit = (rowData = {}) => {
  dialogFormVisible.value = true;
  console.log("rowData", rowData);
  //弹窗打开form 声称是异步的
  nextTick(() => {
    //如果是编辑
    if (rowData) {
      Object.assign(updateForm.value, rowData);
      // updateForm.value = rowData
      console.log("这里是获取编辑数据", rowData);
    }
  });
};

const confirm = async () => {
  console.log("更新内容", updateForm);
  console.log("更新内容", updateForm.value);
  //把updateForm.value给列表的第一列
  let res = await updateOutputTable(updateForm.value);
  console.log("res",res)
  if (res.code == 20000) {
    ElMessage({
      message: "修改成功",
      type: "success",
      duration: 1000
    });
    getOutputtableList();
  } else {
    ElMessage({
      message: "修改失败",
      type: "error",
      duration: 1000
    });
  }
  dialogFormVisible.value = false;
};

//删除
const deleteItem = async (id) => {
  try {
    await ElMessageBox.confirm('是否要该条数据', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    console.log(id);
    await deleteOutputTable(id);
    ElMessage({
      message: '删除成功',
      type: 'success',
      duration: 1000
    });
  } catch (error) {
    // Handle cancel or error
  }
  getOutputtableList();
};

//上传文件
const fieldMapping = {
  "年份":"year",
  "城市":"city",
  "小麦播种面积":"wheatArea",
  "玉米播种面积":	"cornArea",
  "小麦产量":	"wheatProduct",
  "玉米产量":"cornProduct",
  "小麦单位面积产量":"wheatProductUnit",
  "玉米单位面积产量":"cornProductUnit",
}
const uploadedData = ref([])
const uploadDialogVisible = ref(false)
const convertedData = ref([])

function uploadExcel() {
  uploadDialogVisible.value = true;
}
const handleFileChange = (file) => {
  const reader = new FileReader();
  reader.onload = (e) => {
    const data = new Uint8Array(e.target.result);
    const workbook = XLSX.read(data, { type: 'array' });
    const firstSheetName = workbook.SheetNames[0];
    const worksheet = workbook.Sheets[firstSheetName];
    const jsonData = XLSX.utils.sheet_to_json(worksheet);

    // 在读取数据后，处理'监测时间'列并将其转换为UTC时间
    jsonData.forEach((row) => {
      if (row['监测时间']) {
        // 假设 '监测时间' 是字符串或者日期格式
        const localTime = new Date(row['监测时间']);
        
        // 获取年月日、小时、分钟和秒
        const year = localTime.getFullYear();
        const month = String(localTime.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的，+1
        const day = String(localTime.getDate()).padStart(2, '0');
        const hours = String(localTime.getHours()).padStart(2, '0');
        const minutes = String(localTime.getMinutes()).padStart(2, '0');
        const seconds = String(localTime.getSeconds()).padStart(2, '0');
        
        // 将日期时间拼接成 'yyyy-mm-dd hh:mm:ss' 格式
        const formattedTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        
        // 将转换后的时间替换原来的时间
        row['监测时间'] = formattedTime;
      }
    })

    uploadedData.value = jsonData; // 将读取的数据保存到 uploadedData
  };

  reader.readAsArrayBuffer(file.raw);
};

const uploadData = async () => {
  let convertedData = convertFields(uploadedData)
  // 遍历 convertedData 数组，并将每个元素的 id 设置为 null
  convertedData.forEach(item => {
    item.id = 0;
  });
  console.log("convertedData",convertedData);
  uploadOutputTable(convertedData)
    .then(response => {
      console.log('上传成功', response);
      uploadedData.value = []; // 清空上传数据
      uploadDialogVisible.value = false; // 关闭弹窗
      ElMessage({
          message: "修改成功",
          type: "success",
          duration: 1000
        });
      // 可以根据需要进一步处理响应
    })
    .catch(error => {
      console.error('上传失败', error);
      ElMessage({
        message: "修改失败",
        type: "error",
        duration: 1000
      });
      // 你可以通过 error.response 获取详细的失败信息（比如 status 或 message）
      if (error.response) {
        // 请求已发出，服务器响应了状态码，且响应体
        console.error('服务器返回错误:', error.response.data);
      } else if (error.request) {
        // 请求已发出，但没有收到响应
        console.error('没有收到响应:', error.request);
      } else {
        // 发生了一些其他错误
        console.error('请求错误:', error.message);
      }
    });
};

const convertFields = (data) => {
  console.log("datadatadatadata",data.value);
  return data.value.map(row => {
    let convertedRow = {};
    Object.keys(row).forEach(key => {
      const englishKey = fieldMapping[key];
      if (englishKey) {
        // 如果是检测时间字段（detectionTime），则转换为国际时间格式
        // if (englishKey === 'detectionTime') {
        //   convertedRow[englishKey] = formatTimestamp(row[key]); // 格式化时间戳
        // } else {
          convertedRow[englishKey] = row[key];
        // }
      }
    });
    return convertedRow;
  });
};

const formatTimestamp = (timestamp) => {
  const date = new Date(timestamp); // 将时间戳转换为 Date 对象
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  const seconds = date.getSeconds().toString().padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

const convertedDataWithFormattedTime = convertedData.value.map(row => {
  console.log("11111111",convertedData.value)
  return {
    ...row,
    detectionTime: formatTimestamp(row.detectionTime)
  };
});

const selectedItems = ref([]); // 直接使用 ref 定义数组

function handleSelectionChange(selected) {
      selectedItems.value = selected; // 更新选中的项
      // console.log(selectedItems.value);
}
//下载文件
function exportExcel() {
  // 准备数据
  const data = selectedItems.value;

  // 检查数据是否为空
  if (data.length === 0) {
    console.error("没有可导出的数据");
        ElMessage({
        message: "没有可导出的数据",
        type: "error",
        duration: 1000
      });
    return;
  }

  // 创建工作簿
  const worksheet = XLSX.utils.json_to_sheet(data);
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");

  // 导出
  XLSX.writeFile(workbook, "data.xlsx");
}

onMounted(() => {
  getOutputtableList();
});

</script>
<style lang="less">
</style>